<template>
  <div class="params">
    <base-template :breadList="['商品管理', '分类参数']">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="info" show-icon style="background: #fa1; color: #fff" :closable="false"> </el-alert>
      <el-row class="cascaderSelect"> <span>选择商品分类：</span><el-cascader v-model="selectValue" :options="cascaderOptions" :props="props" @change="handleChange"></el-cascader> </el-row>

      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <!-- 动态 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button size="mini" :disabled="!selectValue.length > 0" @click="addParams('动态参数', '添加')"> 添加属性</el-button>
          <!-- 动态 -->
          <el-table :data="tableData" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <!-- tag -->
              <template v-slot="scope">
                <el-tag :key="index" v-for="(tag, index) in scope.row.attr_vals" closable :disable-transitions="false" @close="tagClose(scope.row, index)">
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
            <el-table-column label="操作" width="180">
              <template v-slot="scope">
                <el-button type="primary" size="mini" @click="editParams('动态参数', '修改', scope.row)" class="marginRight">修改</el-button>
                <el-popconfirm title="确定删除吗？" @confirm="removeParams(scope.row)">
                  <el-button type="danger" size="mini" slot="reference">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button size="mini" :disabled="!selectValue.length > 0" @click="addParams('静态属性', '添加')">添加参数</el-button>
          <el-table :data="tableData" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <!-- tag -->
              <template v-slot="scope">
                <el-tag :key="index" v-for="(tag, index) in scope.row.attr_vals" closable :disable-transitions="false" @close="tagClose(scope.row)">
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column label="操作" width="180">
              <template v-slot="scope">
                <el-button type="primary" size="mini" @click="editParams('静态属性', '修改', scope.row)" class="marginRight">修改</el-button>
                <el-popconfirm title="确定删除吗？" @confirm="removeParams(scope.row)">
                  <el-button slot="reference" size="mini"  type="danger">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </base-template>

    <el-dialog :title="inputLabel" :visible.sync="inputVisible" width="460px" :before-close="handleClose">
      <div>
        <label for="" required>
          <h4 class="domInline">{{ inputTitle }}：</h4>
          <el-input class="domWidth300" ref="addRef" v-model="inputValue"></el-input>
        </label>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inputVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BaseTemplate from '../../component/base-template.vue'
export default {
  components: {
    BaseTemplate,
  },
  data() {
    return {
      cascaderOptions: [], //数据
      selectValue: [], //绑定value
      props: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
      },

      activeName: 'many',
      tableData: [],
      // tag
      inputValue: '', //添加 or 编辑
      inputVisible: false,
      inputLabel: '',
      inputTitle: '',
      attr_id: '',
    }
  },
  computed: {
    tempId() {
      if (this.selectValue.length > 0) {
        return this.selectValue[this.selectValue.length - 1]
      } else {
        return 0
      }
    },
  },
  created() {
    this.getCascaderData()
  },
  methods: {
    async getCascaderData() {
      this.cascaderOptions = await this.$store.dispatch('getRequest', { path: '/categories' })
    },
    async handleChange() {
      //级联函数
      const res = await this.$store.dispatch('getRequest', {
        path: `/categories/${this.tempId}/attributes`,
        params: { sel: this.activeName },
      })
      for (let prop in res) {
        if (!res[prop].attr_vals) {
          res[prop].attr_vals = []
        } else {
          res[prop].attr_vals = res[prop].attr_vals.split(',')
        }

        res[prop].inputValue = ''
        res[prop].inputVisible = false
      }
      this.tableData = res
    },
    handleClick(tab, event) {
      //tabs
      if (this.selectValue.length > 0) {
        this.handleChange()
      }
    },

    addParams(val, para) {
      this.inputValue = ''
      this.inputVisible = true
      this.inputTitle = val
      this.inputLabel = para + val
      this.$nextTick(() => {
        this.$refs.addRef.focus()
      })
    },
    editParams(val, para, row) {
      this.addParams(val, para)
      this.inputValue = row.attr_name
      this.attr_id = row.attr_id
    },
    async removeParams(row) {
      const res = await this.$store.dispatch('deleteRequest', { path: `categories/${row.cat_id}/attributes/${row.attr_id}` })
      console.log(res)
      if (res.status == 200) {
        this.$message.success('删除成功')
        this.handleChange()
      } else {
        this.$message.error('删除失败')
      }
    },
    async tagClose(row, index) {
      row.attr_vals.splice(index,1)
     var temp=JSON.parse(JSON.stringify(row.attr_vals))

      const { meta, data } = await this.$store.dispatch('putRequest', {
        path: `categories/${this.tempId}/attributes/${row.attr_id}`,
        params: { attr_name: row.attr_name, attr_sel: this.activeName,attr_vals:temp.join(',') },
      })
      if (meta.status == 200) {
        // this.handleChange()
        this.inputVisible = false
        this.$message.success('添加参数成功')
      } else {
        this.$message.error('添加参数失败')
      }
      console.log(row)
    },

    showInput(row) {
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async handleInputConfirm(row) {
      //编辑展开参数
      let inputValue = row.inputValue
      if (inputValue) {
        row.attr_vals.push(inputValue)
        let temp = row.attr_vals.join(',')

        const { meta } = await this.$store.dispatch('putRequest', {
          path: `/categories/${row.cat_id}/attributes/${row.attr_id}`,
          params: { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: temp },
        })
        if (meta.status == 200) {
          this.$message.success('更新参数成功')
        } else {
          this.$message.error('更新参数失败')
        }
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    handleClose(done) {
      //dialog弹窗
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    async submitParams() {
      //添加   编辑
      if (this.inputValue) {
        console.log(this.inputTitle)
        if (this.inputLabel == '添加动态参数' || this.inputLabel == '添加静态属性') {
          const { meta, data } = await this.$store.dispatch('postRequest', { path: `categories/${this.tempId}/attributes`, params: { attr_name: this.inputValue, attr_sel: this.activeName } })
          if (meta.status == 201) {
            this.handleChange()
            this.inputVisible = false
            this.$message.success('添加参数成功')
          } else {
            this.$message.error('添加参数失败')
          }
        } else {
          const { meta, data } = await this.$store.dispatch('putRequest', {
            path: `categories/${this.tempId}/attributes/${this.attr_id}`,
            params: { attr_name: this.inputValue, attr_sel: this.activeName },
          })
          if (meta.status == 200) {
            this.handleChange()
            this.inputVisible = false
            this.$message.success('修改参数成功')
          } else {
            this.$message.error('修改参数失败')
          }
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
div.params {
  .el-row.cascaderSelect {
    margin-top: 20px;
  }
  .el-tag {
    margin: 10px 0 0 10px;
  }
  .button-new-tag {
    margin: 10px 0 0 10px;

    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin: 10px 0 0 10px;
    vertical-align: bottom;
  }
}
</style>
